package com.apes.bi.service;

import com.alibaba.fastjson.JSONObject;
import com.apes.bi.model.Canvas;
import com.apes.bi.repository.CanvasRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.spec.PredicateBuilder;
import com.apes.framework.jpa.spec.Specifications;
import com.apes.framework.jpa.spec.model.Group;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service("canvasService")

public class CanvasService extends DomainService {

    @Autowired
    CanvasRepository canvasRepository;

    public Canvas create(SimpleRequest request){
        Canvas canvas = request.getO(Canvas.class);
        return canvasRepository.save(canvas);
    }


    public Canvas update(SimpleRequest request){
        Canvas canvas = request.getO(Canvas.class);
        return canvasRepository.saveAndFlush(canvas);
    }


    /***
     * 更新所有看板
     * @param request
     * @return
     */
    public List<Canvas> updateAll(SimpleRequest request){
        List<Canvas> canvasList = request.getA(Canvas.class);

        return canvasList.stream()
                .map(item -> canvasRepository.saveAndFlush(item) )
                .collect(Collectors.toList());
    }

    public String delete(SimpleRequest request){
        Canvas canvas = request.getO(Canvas.class);
        canvasRepository.delete(canvas);
        return "删除成功";
    }


    public List<Canvas> findAllForAuth(SimpleRequest request){
        JSONObject json = request.getJO();

        if( json.getString("userId")  == null || json.getString("postId") == null ) throw new RuntimeException("用户编码和岗位编码不能为空");

        // 拼接权限的查询列表
        PredicateBuilder pb = Specifications.or();;
        pb.eq("canvasPostPermits.post.id", json.getString("postId"));
        pb.eq("canvasUserPermits.user.id", json.getString("userId"));
        pb.build(false);

        Sort sort = new Sort(Sort.Direction.ASC, "id");

        return canvasRepository.findAll(pb.build(true), sort);
    }

}
